package com.jt.aop;

import com.jt.anno.Pri;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
public class SpringAOP {

    private List<String> list = new ArrayList<>(); //单机版本
    //java基础: ArrayList是线程不安全的.

    @PostConstruct
    public void init(){
        list.add("add");        //add操作
        list.add("update");     //update操作
    }

    /**
     * 1. 获取方法中的注解@Pri(name = "add")
     * 2. 获取权限的名称  name = "add"
     * 3. 判断list集合中是否有该权限.
     *          true: 有权限  执行目标方法
     *          false: 输出没有权限直接跳过.
     * 4. 规则:
     *      1. 如果有多个参数 则joinPoint必须位于第一位!!!! args[0]
     *    变态写法:
     *      可以直接写注解的名称,这样的话 可以直接为注解赋值.
     *
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(pri)") //只是拦截注解,获取注解的数据
    public Object around2(ProceedingJoinPoint joinPoint,Pri pri) throws Throwable {
        String name = pri.name();
        System.out.println("用户的权限:"+name);
        //判断list集合中是否有权限
        if(list.contains(name)){
            //true
            Object result = joinPoint.proceed();
            return result;
        }else{
            System.out.println("告知用户没有权限!!!!");
        }
        return null;
    }






    //@Around("execution(* com.jt.service..*.*(..))")
    public Object around1(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        Class target = joinPoint.getTarget().getClass();
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args  = joinPoint.getArgs();
        System.out.println("耗时:"+(endTime - startTime));
        System.out.println("类型:"+ target);
        System.out.println("类的名称:"+ className);
        System.out.println("方法名称:"+ methodName);
        System.out.println("参数:"+ Arrays.toString(args));
        System.out.println("返回值:"+ result);
        return result;
    }


}
